/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jmail.window;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.swing.JFileChooser;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import jmail.Config;
import jmail.ReceiveEmail;
import jmail.SendMail;
import jmail.file.DumpExcel;
import jmail.file.Students;
import jmail.file.XmlData;
import jmail.file.ZipCompress;
import org.jdom.Element;
import org.jdom.JDOMException;

/**
 *
 * @author iflamed
 */
public class JMainFrame extends javax.swing.JFrame {

    private boolean receiver = false, stopSend = false;
    private ReceiveEmail re;
    private SendMail sm;
    private int total, current;
    private Vector name = new Vector(), allname = new Vector(), dname = new Vector();
    private Vector senddata;
    private Vector data, alldata, dtdata;
    private Queue<Vector> sendMails = new ConcurrentLinkedQueue<Vector>();
    private ReceiveTableModel myModel = new ReceiveTableModel(data, name);
    private ViewAllModel vaModel = new ViewAllModel(alldata, allname);
    private DetailModel dtModel = new DetailModel(dtdata, dname);
    private int currentRows = 0;
    private String totalscore, stuname, stunum, detailfile;

    /**
     * Creates new form JMainFrame
     */
    public JMainFrame() {
        name.addElement("收取进度");
        name.addElement("姓名");
        name.addElement("学号");
        name.addElement("作业编号");
        name.addElement("得分");
        name.addElement("发送者");
        name.addElement("回复邮件");
        allname.addElement("姓名");
        allname.addElement("学号");
        allname.addElement("总分");
        allname.addElement("作业量");
        allname.addElement("详细文件");
        allname.addElement("查看文件");
        dname.addElement("学号");
        dname.addElement("姓名");
        dname.addElement("作业编号");
        dname.addElement("作业得分");
        dname.addElement("获得总分");
        dname.addElement("查看附件");
        dname.addElement("hiddenscore");
        initComponents();
        this.content.remove(this.mailScrollPane);
        this.content.remove(this.viewScrollPane);
        this.content.remove(this.detailScrollPane);
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dialog = new javax.swing.JDialog();
        dialogcontent = new javax.swing.JPanel();
        smtp = new javax.swing.JLabel();
        smtpserver = new javax.swing.JTextField();
        smtpPort = new javax.swing.JSpinner();
        portLabel = new javax.swing.JLabel();
        pop3Label = new javax.swing.JLabel();
        pop3Server = new javax.swing.JTextField();
        portLabel1 = new javax.swing.JLabel();
        pop3Port = new javax.swing.JSpinner();
        confirm = new javax.swing.JButton();
        dismiss = new javax.swing.JButton();
        fileLabel = new javax.swing.JLabel();
        directory = new javax.swing.JTextField();
        getdir = new javax.swing.JButton();
        mailLabel = new javax.swing.JLabel();
        email = new javax.swing.JTextField();
        nameLabel = new javax.swing.JLabel();
        username = new javax.swing.JTextField();
        passLabel = new javax.swing.JLabel();
        password = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        perScore = new javax.swing.JTextField();
        dirChooser = new javax.swing.JFileChooser();
        menu = new javax.swing.JPanel();
        config = new javax.swing.JButton();
        receive = new javax.swing.JButton();
        view = new javax.swing.JButton();
        list = new javax.swing.JButton();
        export = new javax.swing.JButton();
        content = new javax.swing.JPanel();
        mailScrollPane = new javax.swing.JScrollPane();
        receiveTable = new javax.swing.JTable();
        viewScrollPane = new javax.swing.JScrollPane();
        viewAllTable = new javax.swing.JTable();
        detailScrollPane = new javax.swing.JScrollPane();
        detailTable = new javax.swing.JTable();
        ConsoleScrollPane = new javax.swing.JScrollPane();
        ConsoleTextArea = new javax.swing.JTextArea();

        dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        dialog.setTitle("输入配置信息");
        dialog.setBackground(new java.awt.Color(204, 204, 255));
        dialog.setBounds(new java.awt.Rectangle(0, 0, 400, 400));
        dialog.setModal(true);
        dialog.setResizable(false);
        dialog.setUndecorated(true);

        dialogcontent.setBackground(new java.awt.Color(204, 204, 255));
        dialogcontent.setPreferredSize(new java.awt.Dimension(411, 380));

        smtp.setText("smtp服务器地址：");

        smtpserver.setText("smtp.126.com");
        smtpserver.setMaximumSize(new java.awt.Dimension(6, 20));
        smtpserver.setPreferredSize(new java.awt.Dimension(6, 20));

        smtpPort.setValue(25);

        portLabel.setText("端口：");

        pop3Label.setText("pop3服务器地址：");

        pop3Server.setText("pop3.126.com");
        pop3Server.setMaximumSize(new java.awt.Dimension(6, 20));
        pop3Server.setPreferredSize(new java.awt.Dimension(6, 20));

        portLabel1.setText("端口：");

        pop3Port.setValue(110);

        confirm.setText("确认");
        confirm.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                confirmMouseClicked(evt);
            }
        });

        dismiss.setText("关闭");
        dismiss.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                dismissMouseClicked(evt);
            }
        });

        fileLabel.setText("     文件保存目录：");

        directory.setMaximumSize(new java.awt.Dimension(6, 20));
        directory.setScrollOffset(17);

        getdir.setText("Browse");
        getdir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                getdirMouseClicked(evt);
            }
        });

        mailLabel.setText("邮箱：");

        email.setText("test@126.com");
        email.setMaximumSize(new java.awt.Dimension(6, 20));
        email.setPreferredSize(new java.awt.Dimension(6, 20));

        nameLabel.setText("用户名：");

        username.setText("test");
        username.setMaximumSize(new java.awt.Dimension(6, 20));
        username.setPreferredSize(new java.awt.Dimension(6, 20));

        passLabel.setText("密码：");

        jLabel1.setText("每次作业分数：");

        perScore.setText("10");

        javax.swing.GroupLayout dialogcontentLayout = new javax.swing.GroupLayout(dialogcontent);
        dialogcontent.setLayout(dialogcontentLayout);
        dialogcontentLayout.setHorizontalGroup(
            dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, dialogcontentLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(confirm)
                .addGap(68, 68, 68)
                .addComponent(dismiss)
                .addGap(105, 105, 105))
            .addGroup(dialogcontentLayout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(passLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(nameLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(mailLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(fileLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pop3Label, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(smtp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(dialogcontentLayout.createSequentialGroup()
                        .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(directory, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(username, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(password)
                            .addComponent(email, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(perScore, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addComponent(getdir)
                        .addGap(77, 77, 77))
                    .addGroup(dialogcontentLayout.createSequentialGroup()
                        .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(smtpserver, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                            .addComponent(pop3Server, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE))
                        .addGap(26, 26, 26)
                        .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(dialogcontentLayout.createSequentialGroup()
                                .addComponent(portLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(smtpPort))
                            .addGroup(dialogcontentLayout.createSequentialGroup()
                                .addComponent(portLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(pop3Port, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())))
        );

        dialogcontentLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {pop3Label, smtp});

        dialogcontentLayout.setVerticalGroup(
            dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dialogcontentLayout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(smtp)
                    .addComponent(smtpserver, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(smtpPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(portLabel))
                .addGap(18, 18, 18)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pop3Label)
                    .addComponent(pop3Server, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(portLabel1)
                    .addComponent(pop3Port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(directory, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(getdir)
                    .addComponent(fileLabel))
                .addGap(18, 18, 18)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(mailLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nameLabel)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passLabel)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(perScore, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                .addGroup(dialogcontentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirm)
                    .addComponent(dismiss))
                .addContainerGap())
        );

        dialogcontentLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {pop3Server, smtpserver});

        dialogcontentLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {directory, email, password, perScore, username});

        fileLabel.getAccessibleContext().setAccessibleName(" 文件保存目录：");

        javax.swing.GroupLayout dialogLayout = new javax.swing.GroupLayout(dialog.getContentPane());
        dialog.getContentPane().setLayout(dialogLayout);
        dialogLayout.setHorizontalGroup(
            dialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 411, Short.MAX_VALUE)
            .addGroup(dialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(dialogLayout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(dialogcontent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );
        dialogLayout.setVerticalGroup(
            dialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 380, Short.MAX_VALUE)
            .addGroup(dialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(dialogLayout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(dialogcontent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );

        dirChooser.setDialogTitle("选择文件目录");
        dirChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("java 教育邮件管理系统");
        setName("mainframe");
        setPreferredSize(new java.awt.Dimension(800, 650));
        setResizable(false);

        menu.setLayout(new java.awt.GridLayout(1, 0, 15, 0));

        config.setText("设置");
        config.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                configMouseClicked(evt);
            }
        });
        menu.add(config);

        receive.setText("收取邮件");
        receive.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                receiveMouseClicked(evt);
            }
        });
        menu.add(receive);

        view.setText("查看所有");
        view.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                viewMouseClicked(evt);
            }
        });
        menu.add(view);

        list.setText("导出所有文件并压缩");
        list.setActionCommand("导出文件并压缩");
        list.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listMouseClicked(evt);
            }
        });
        menu.add(list);

        export.setText("导出成绩");
        export.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                exportMouseClicked(evt);
            }
        });
        menu.add(export);

        content.setBackground(new java.awt.Color(153, 153, 255));
        content.setPreferredSize(new java.awt.Dimension(600, 600));

        receiveTable.setModel(myModel);
        receiveTable.getColumnModel().getColumn(0).setMinWidth(20);
        receiveTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        receiveTable.getColumnModel().getColumn(2).setMinWidth(50);
        receiveTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        receiveTable.getColumnModel().getColumn(4).setMinWidth(20);
        receiveTable.getColumnModel().getColumn(4).setPreferredWidth(40);
        receiveTable.getColumnModel().getColumn(5).setMinWidth(100);
        receiveTable.getColumnModel().getColumn(5).setMaxWidth(350);
        receiveTable.getColumnModel().getColumn(5).setPreferredWidth(300);
        receiveTable.getColumnModel().getColumn(6).setMinWidth(20);
        receiveTable.getColumnModel().getColumn(6).setPreferredWidth(60);
        mailScrollPane.setViewportView(receiveTable);

        viewAllTable.setModel(vaModel);
        viewAllTable.getColumnModel().getColumn(0).setMinWidth(0);
        viewAllTable.getColumnModel().getColumn(0).setPreferredWidth(20);
        viewAllTable.getColumnModel().getColumn(1).setMinWidth(30);
        viewAllTable.getColumnModel().getColumn(1).setPreferredWidth(50);
        viewAllTable.getColumnModel().getColumn(2).setMinWidth(10);
        viewAllTable.getColumnModel().getColumn(2).setPreferredWidth(20);
        viewAllTable.getColumnModel().getColumn(3).setMinWidth(10);
        viewAllTable.getColumnModel().getColumn(3).setPreferredWidth(20);
        viewAllTable.getColumnModel().getColumn(4).setMinWidth(150);
        viewAllTable.getColumnModel().getColumn(4).setPreferredWidth(250);
        viewAllTable.getColumnModel().getColumn(5).setMinWidth(50);
        viewAllTable.getColumnModel().getColumn(5).setPreferredWidth(100);
        viewAllTable.setRowHeight(50);
        viewAllTable.getColumnModel().getColumn(5).setCellRenderer(new ExtensionCellRenderer(this.viewAllTable,5));
        viewScrollPane.setViewportView(viewAllTable);

        detailTable.setModel(dtModel);
        detailTable.setRowHeight(50);
        //System.out.println(detailTable.getColumnCount());
        detailTable.getColumnModel().getColumn(5).setCellRenderer(new ExtensionCellRenderer(this.detailTable,5));
        this.dtModel.addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {

                int col = e.getColumn();
                int row = e.getFirstRow();
                if (col == 3) {
                    updateTscore(row, col);
                }
            }
        });
        detailScrollPane.setViewportView(detailTable);

        javax.swing.GroupLayout contentLayout = new javax.swing.GroupLayout(content);
        content.setLayout(contentLayout);
        contentLayout.setHorizontalGroup(
            contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, contentLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(detailScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 733, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(22, 22, 22))
            .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(contentLayout.createSequentialGroup()
                    .addGap(23, 23, 23)
                    .addComponent(mailScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 733, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(24, Short.MAX_VALUE)))
            .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(contentLayout.createSequentialGroup()
                    .addGap(24, 24, 24)
                    .addComponent(viewScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 729, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(23, Short.MAX_VALUE)))
        );

        contentLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {detailScrollPane, mailScrollPane, viewScrollPane});

        contentLayout.setVerticalGroup(
            contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(detailScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(contentLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(mailScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(32, Short.MAX_VALUE)))
            .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(contentLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(viewScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 483, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        contentLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {detailScrollPane, mailScrollPane, viewScrollPane});

        ConsoleTextArea.setColumns(20);
        ConsoleTextArea.setEditable(false);
        ConsoleTextArea.setRows(3);
        ConsoleTextArea.setCaretColor(new java.awt.Color(102, 0, 0));
        ConsoleTextArea.setDisabledTextColor(new java.awt.Color(0, 204, 51));
        ConsoleScrollPane.setViewportView(ConsoleTextArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(menu, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                    .addComponent(content, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                    .addComponent(ConsoleScrollPane))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(menu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addComponent(content, javax.swing.GroupLayout.PREFERRED_SIZE, 505, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ConsoleScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void configMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_configMouseClicked
        // TODO add your handling code here:
        this.smtpserver.setText(Config.getProps("smtpserver"));
        this.smtpPort.setValue(Integer.parseInt(Config.getProps("smtpport")));
        this.pop3Server.setText(Config.getProps("pop3server"));
        this.pop3Port.setValue(Integer.parseInt(Config.getProps("pop3port")));
        this.directory.setText(Config.getProps("jmail.dir"));
        this.email.setText(Config.getProps("email"));
        this.username.setText(Config.getProps("username"));
        this.password.setText(Config.getProps("password"));
        this.perScore.setText(Config.getProps("perscore"));
        this.dialog.setLocationRelativeTo(this.content);
        this.dialog.setVisible(true);
        this.dialog.repaint();
    }//GEN-LAST:event_configMouseClicked

    private void confirmMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_confirmMouseClicked
        // TODO add your handling code here:
        String smtpServer = this.smtpserver.getText();
        String smtpport = this.smtpPort.getValue().toString();
        String pop3server = this.pop3Server.getText();
        String pop3port = this.pop3Port.getValue().toString();
        String dir = this.directory.getText();
        String eMail = this.email.getText();
        String userName = this.username.getText();
        String passWord = String.valueOf(this.password.getPassword());
        String perscore = this.perScore.getText();
        Config.addProp("smtpserver", smtpServer);
        Config.addProp("smtpport", smtpport);
        Config.addProp("pop3server", pop3server);
        Config.addProp("pop3port", pop3port);
        Config.addProp("jmail.dir", dir);
        Config.addProp("email", eMail);
        Config.addProp("username", userName);
        Config.addProp("password", passWord);
        Config.addProp("perscore", perscore);
        Config.dumpProps();
        this.dialog.setVisible(false);
        this.dialog.repaint();
    }//GEN-LAST:event_confirmMouseClicked

    private void getdirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_getdirMouseClicked
        // TODO add your handling code here:
        this.dirChooser.setDialogTitle("选择文件目录");
        this.dirChooser.setToolTipText("选择文件目录");
        this.dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        this.dirChooser.showOpenDialog(content);
        this.dirChooser.setVisible(true);
        this.dirChooser.repaint();
        this.directory.setText(this.dirChooser.getSelectedFile().getAbsolutePath());
        this.dialog.repaint();
    }//GEN-LAST:event_getdirMouseClicked

    private void dismissMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dismissMouseClicked
        // TODO add your handling code here:
        this.dialog.setVisible(false);
        this.dialog.repaint();
    }//GEN-LAST:event_dismissMouseClicked

    private void receiveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_receiveMouseClicked
        // TODO add your handling code here:
        if (!this.receiver) {
            this.content.removeAll();
            this.content.add(this.mailScrollPane);
            this.content.repaint();
            MessageCallBack mcb = new MessageCallBack();
            re = new ReceiveEmail(Config.getProps("pop3server"),
                    "pop3",
                    Config.getProps("username"),
                    Config.getProps("password"),
                    Config.getProps("pop3port"),
                    "inbox", mcb);
            sm = new SendMail(Config.getProps("smtpserver"),
                    Config.getProps("email"),
                    Config.getProps("username"),
                    Config.getProps("password"),
                    mcb, sendMails);
            Thread treceiver = new Thread(re);
            treceiver.setName("Receiver");
            this.receive.setText("停止收取");
            this.receiver = true;
            treceiver.start();
            if (!isThreadCurrent("Sender")) {
                Thread tsender = new Thread(sm);
                tsender.setName("Sender");
                this.stopSend = false;
                tsender.start();
            }
        } else {
            //this.content.remove(this.mailScrollPane);
            this.receive.setText("收取邮件");
            this.receiver = false;
            this.stopSend = true;
            re.stopRunning();
            this.content.repaint();
            System.out.println("paint complete");
            //TODO add a variable to record the current total row number;
        }
    }//GEN-LAST:event_receiveMouseClicked

    private void viewMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_viewMouseClicked
        // TODO add your handling code here:
        this.content.removeAll();
        this.vaModel.setRowCount(0);
        this.viewAllTable.revalidate();
        this.content.add(this.viewScrollPane);
        Students stu = new Students();
        List<Element> students = stu.getAllStudents();
        Element student;
        Iterator it = students.iterator();
        while (it.hasNext()) {
            student = (Element) it.next();
            alldata = new Vector();
            this.alldata.addElement(student.getChildText("studentName"));
            this.alldata.addElement(student.getChildText("studentNumber"));
            this.alldata.addElement(student.getChildText("totalscore"));
            this.alldata.addElement(student.getChildText("assigncount"));
            this.alldata.addElement(student.getChildText("detailfilepath"));
            this.alldata.addElement(new Detail(student.getChildText("detailfilepath")));
            this.vaModel.addRow(alldata);
        }
        this.content.repaint();
    }//GEN-LAST:event_viewMouseClicked

    private void listMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listMouseClicked
        try {
            // TODO add your handling code here:
            if (!isThreadCurrent("Compresser")) {
                this.dirChooser.setDialogTitle("选择文件目录，并输入文件名");
                this.dirChooser.setToolTipText("选择文件目录，并输入文件名");
                this.dirChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                this.dirChooser.showOpenDialog(content);
                this.dirChooser.setVisible(true);
                this.dirChooser.repaint();
                if (this.dirChooser.getSelectedFile() != null) {
                    ZipCompress zcp = new ZipCompress(this.dirChooser.getSelectedFile().getAbsolutePath() + ".zip", Config.getProps("jmail.dir") + "\\");
                    Thread cper = new Thread(zcp);
                    cper.setName("Compresser");
                    cper.start();
                }
                this.dialog.repaint();
            }
        } catch (Exception ex) {
            Logger.getLogger(JMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_listMouseClicked

    private void exportMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportMouseClicked
        try {
            List<Vector> data = new LinkedList<Vector>();
            List students = new LinkedList();
            Students dataindex = new Students();
            students = dataindex.getAllStudents();
            Vector label = new Vector();
            label.addElement("学号");
            label.addElement("姓名");
            label.addElement("作业一");
            label.addElement("作业二");
            label.addElement("作业三");
            label.addElement("作业四");
            label.addElement("作业五");
            label.addElement("作业六");
            label.addElement("作业七");
            label.addElement("作业八");
            label.addElement("作业九");
            label.addElement("作业十");
            label.addElement("作业十一");
            label.addElement("作业十二");
            label.addElement("作业十三");
            label.addElement("作业十四");
            label.addElement("作业十五");
            label.addElement("作业十六");
            label.addElement("作业十七");
            label.addElement("作业十八");
            label.addElement("总分");
            data.add(label);
            Iterator stu = students.iterator();
            while (stu.hasNext()) {
                Element student = (Element) stu.next();
                try {
                    XmlData detail = new XmlData(student.getChildText("detailfilepath"));
                    List scoredata = detail.getDetail();
                    Vector score = new Vector(21);
                    for (int i = 0; i < 21; i++) {
                        if (i == 0 || i == 1 || i == 20) {
                            score.add("");
                        } else {
                            score.add(0);
                        }
                    }
                    score.setElementAt(((Element) scoredata.get(1)).getText(), 0);
                    score.setElementAt(((Element) scoredata.get(2)).getText(), 1);
                    List<Element> assigns = ((Element) scoredata.get(3)).getChildren();
                    Iterator<Element> it = assigns.iterator();
                    while (it.hasNext()) {
                        System.out.println("output assign score");
                        Element assign = it.next();
                        String assignname = assign.getChildText("assign");
                        int key = label.indexOf(assignname);
                        System.err.println("value key is:" + assignname + ":" + key);
                        score.setElementAt(Integer.parseInt(assign.getChildText("score")), key);
                    }
                    score.setElementAt(((Element) scoredata.get(0)).getText(), 20);
                    data.add(score);
                } catch (JDOMException ex) {
                    Logger.getLogger(JMainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            this.dirChooser.setDialogTitle("选择文件目录，并输入文件名");
            this.dirChooser.setToolTipText("选择文件目录，并输入文件名");
            this.dirChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            this.dirChooser.showOpenDialog(content);
            this.dirChooser.setVisible(true);
            this.dirChooser.repaint();
            if(this.dirChooser.getSelectedFile() != null){
            DumpExcel de = new DumpExcel(this.dirChooser.getSelectedFile().getAbsolutePath() + ".xls");
            de.setData(data);
            if (!isThreadCurrent("Exportor")) {
                Thread expor = new Thread(de);
                expor.setName("Exportor");
                expor.start();
            }
            }
        } catch (IOException ex) {
            Logger.getLogger(JMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_exportMouseClicked

    public void showDetail(String detailfile) {
        try {
            this.content.removeAll();
            this.dtModel.setRowCount(0);
            this.detailTable.revalidate();
            this.content.add(this.detailScrollPane);
            this.detailfile = detailfile;
            XmlData detail = new XmlData(detailfile);
            List<Element> baseinfo = detail.getDetail();
            stuname = baseinfo.get(2).getText();
            stunum = baseinfo.get(1).getText();
            totalscore = baseinfo.get(0).getText();
            Element dinfo, attach;
            Iterator it = baseinfo.get(3).getChildren().iterator();
            while (it.hasNext()) {
                dinfo = (Element) it.next();
                dtdata = new Vector();
                this.dtdata.addElement(stunum);
                this.dtdata.addElement(stuname);
                this.dtdata.addElement(dinfo.getChildText("assign"));
                this.dtdata.addElement(dinfo.getChildText("score"));
                this.dtdata.addElement(totalscore);
                List<Element> attachs = dinfo.getChild("attachs").getChildren();
                String filepath = attachs.get(0).getChildText("filepath");
                this.dtdata.addElement(new Cmdetail(filepath));
                this.dtdata.addElement(dinfo.getChildText("score"));
                this.dtModel.addRow(dtdata);
            }
            this.detailTable.getColumnModel().getColumn(6).setMinWidth(0);
            this.detailTable.getColumnModel().getColumn(6).setMaxWidth(0);
            this.detailTable.getColumnModel().getColumn(6).setWidth(0);
            this.content.repaint();
        } catch (JDOMException ex) {
            Logger.getLogger(JMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void updateTscore(int row, int col) {
        try {
            int avalue = Integer.parseInt(totalscore);
            int svalue = Integer.parseInt((String) this.detailTable.getValueAt(row, col + 3));
            int nvalue = Integer.parseInt((String) this.detailTable.getValueAt(row, col));
            avalue = avalue - svalue + nvalue;
            totalscore = String.valueOf(avalue);
            this.detailTable.setValueAt(String.valueOf(nvalue), row, col + 3);
            for (int i = 0; i < this.detailTable.getRowCount(); i++) {
                this.detailTable.setValueAt(totalscore, i, col + 1);
            }
            this.detailTable.revalidate();
            this.content.repaint();
            XmlData detail = new XmlData(this.detailfile);
            detail.updateScore((String) this.detailTable.getValueAt(row, 2), String.valueOf(nvalue));
            //System.out.println("totalscore:" + totalscore);
        } catch (JDOMException ex) {
            Logger.getLogger(JMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JMainFrame().setVisible(true);
            }
        });
    }

    public class Cmdetail {

        private String filepath;

        public Cmdetail(String file) {
            filepath = file;
        }

        @Override
        public String toString() {
            try {
                Runtime.getRuntime().exec(
                        "rundll32 SHELL32.DLL,ShellExec_RunDLL "
                        + "Explorer.exe /select," + filepath);
                return "查看目录";
            } catch (IOException ex) {
                Logger.getLogger(JMainFrame.class.getName()).log(Level.SEVERE, null, ex);
                return "查看目录";
            }
        }
    }

    public class Detail {

        private String detailfile;

        public Detail(String detailfile) {
            this.detailfile = detailfile;
        }

        public void sayHello() {
            System.out.println("hello," + name);
        }

        @Override
        public String toString() {
            showDetail(detailfile);
            return "查看文件";
        }
    }
    //回调对象，用于反馈已经下载的信息

    public class MessageCallBack {

        public void update(int total, int current, Map m) throws MessagingException {
            JMainFrame.this.setTotal(total);
            JMainFrame.this.setCurrent(current);
            JMainFrame.this.currentRows = JMainFrame.this.receiveTable.getRowCount();
            data = new Vector();
            senddata = new Vector();
            data.addElement(current + "/" + total);
            data.addElement(m.get("stuName"));
            data.addElement(m.get("number"));
            data.addElement(m.get("assginnum"));
            data.addElement(m.get("score"));
            data.addElement(m.get("mailsender"));
            data.addElement(m.get("false"));
            senddata.addElement(m.get("mailsender"));
            String mailcontent = m.get("stuName") + "," + m.get("number")
                    + "\t你好！你发送的邮件：" + m.get("assginnum") + "\t我已经收到并查阅";
            senddata.addElement(mailcontent);
            senddata.addElement("Reply-To:" + m.get("stuName") + "  " + m.get("number") + "  " + m.get("assginnum"));
            senddata.addElement(JMainFrame.this.currentRows);
            sendMails.offer(senddata);
            JMainFrame.this.myModel.addRow(data);
            if (total == current) {
                JMainFrame.this.receive.setText("收取邮件");
            }
            JMainFrame.this.receiveTable.revalidate();
        }

        public void setStopSend() {
            JMainFrame.this.stopSend = true;
        }

        public boolean getStopSend() {
            return JMainFrame.this.stopSend;
        }

        public void updateMailStatu(int row, int collumn, boolean statu) {
            if (statu) {
                JMainFrame.this.myModel.setValueAt("已回复", row, collumn);
            } else {
                JMainFrame.this.myModel.setValueAt("未回复", row, collumn);
            }
            JMainFrame.this.receiveTable.revalidate();
        }
    }

    public int getCurrent() {
        return current;
    }

    public void setCurrent(int current) {
        this.current = current;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    private boolean isThreadCurrent(String name) {

        int n = Thread.activeCount();
        Thread[] threads = new Thread[n];
        Thread.enumerate(threads);
        boolean b = false;
        for (int i = 0; i < threads.length; i++) {
            Thread thread = threads[i];
            if (thread.getName().equals(name)) {

                b = true;
                if("Receiver".equals(name)){
                    this.ConsoleTextArea.append("已经开始接收邮件了，请等待一下\n");
                }else if("Sender".equals(name)){
                    this.ConsoleTextArea.append("程序正在自动回复邮件！\n");
                }else if("Compresser".equals(name)){
                    this.ConsoleTextArea.append("程序正在进行文件压缩！\n");
                }else if("Exportor".equals(name)){
                    this.ConsoleTextArea.append("程序正在导出成绩到EXCEL表格！\n");
                }
                this.ConsoleTextArea.repaint();
            }else{
                if("Receiver".equals(name) && i == threads.length-1){
                    this.ConsoleTextArea.append("接收邮件，确保已经连接网络！\n");
                }else if("Sender".equals(name) && i == threads.length-1){
                    this.ConsoleTextArea.append("回复邮件，确保已经连接网络！\n");
                }else if("Compresser".equals(name) && i == threads.length-1){
                    this.ConsoleTextArea.append("程序即将开始文件压缩！\n");
                }else if("Exportor".equals(name) && i == threads.length-1){
                    this.ConsoleTextArea.append("程序即将开始导出成绩到EXCEL表格！\n");
                }
                this.ConsoleTextArea.repaint();
            }
        }
        return b;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane ConsoleScrollPane;
    private javax.swing.JTextArea ConsoleTextArea;
    private javax.swing.JButton config;
    private javax.swing.JButton confirm;
    private javax.swing.JPanel content;
    private javax.swing.JScrollPane detailScrollPane;
    private javax.swing.JTable detailTable;
    private javax.swing.JDialog dialog;
    private javax.swing.JPanel dialogcontent;
    private javax.swing.JFileChooser dirChooser;
    private javax.swing.JTextField directory;
    private javax.swing.JButton dismiss;
    private javax.swing.JTextField email;
    private javax.swing.JButton export;
    private javax.swing.JLabel fileLabel;
    private javax.swing.JButton getdir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton list;
    private javax.swing.JLabel mailLabel;
    private javax.swing.JScrollPane mailScrollPane;
    private javax.swing.JPanel menu;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JLabel passLabel;
    private javax.swing.JPasswordField password;
    private javax.swing.JTextField perScore;
    private javax.swing.JLabel pop3Label;
    private javax.swing.JSpinner pop3Port;
    private javax.swing.JTextField pop3Server;
    private javax.swing.JLabel portLabel;
    private javax.swing.JLabel portLabel1;
    private javax.swing.JButton receive;
    private javax.swing.JTable receiveTable;
    private javax.swing.JLabel smtp;
    private javax.swing.JSpinner smtpPort;
    private javax.swing.JTextField smtpserver;
    private javax.swing.JTextField username;
    private javax.swing.JButton view;
    private javax.swing.JTable viewAllTable;
    private javax.swing.JScrollPane viewScrollPane;
    // End of variables declaration//GEN-END:variables
}
